/**
 * 
 */
package com.et114.modules.org.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
   
import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

//import com.et114.core.utility.URLEncoder;

import org.apache.commons.beanutils.PropertyUtils;

import com.et114.components.acegi.Constants;
import com.et114.components.ectable.EXTableUtils;
import com.et114.components.ectable.EctableConverts;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.utility.GetterUtil;
import com.et114.modules.org.form.RoleForm;
import com.et114.modules.org.message.OrgMessageManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.services.RoleManager;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.vo.FuncComponentVo;
import com.et114.modules.org.vo.FuncRoleRelVo;
import com.et114.modules.org.vo.FunctionVo;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.org.vo.UserEmplyVo;
import com.et114.modules.system.dictionary.DictionaryCache;
import com.et114.modules.system.dictionary.vo.BizOption;
import com.et114.modules.system.dictionary.vo.BizType;

import java.util.List;

/*
 * @author guanhw
 */
public class RoleAction extends BaseDispatchAction {
	
	
	/**
	 * 生成角色首页 
	 */
	public  ActionForward indexRoles ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		    BizType bizType = DictionaryCache.getInstance ( ).getBizType ( Constants.ROLE_DIC_BIZ_KEY ) ;
			List soptions = OrgFactory.getRoleManager ( ).getRoleTypes (  )  ;
			request.setAttribute ( "options" , soptions ) ;	
			
			request.setAttribute ( "bizType" , bizType ) ;
			request.setAttribute ( "options" , soptions ) ;	
			return mapping.findForward (  "roleManager"  ) ;
	}
	
	/**
	 * 取角色列表
	 */
	public  ActionForward loadRoles ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;		 
		RoleVo role = new RoleVo();
		short roleType = 0;
		PropertyUtils.copyProperties ( role , roleForm ) ;
		EXTableUtils.initLimitPage(  role , request ) ;
		Long lr = roleManager.loadRolesRows (   role  ) ;
		role.setTotalRows ( lr.intValue ( ) ) ; 
		EXTableUtils.setLimitRowAttributes(  role , request ) ;
		
		
		List roles = roleManager.getLimitRoles ( role ) ;
		for ( java.util.Iterator iter = roles.iterator ( ) ; iter.hasNext ( ) ;  ) {
			role = ( RoleVo )  iter.next ( ) ; 
			roleType = role.getRoleType ( ) ; 
			String roleTypeName = DictionaryCache.getInstance ( ).getBizOptionName ( Constants.ROLE_DIC_BIZ_KEY  , String.valueOf ( roleType ) ) ;
			role.setRoleTypeName ( roleTypeName ) ;
		}
		request.setAttribute ( "roles" , roles ) ; 
		request.setAttribute ( "roleType" , String.valueOf ( roleType ) ) ; 
		if ( roleForm.getRoleName ( ) != null ) request.setAttribute ( "roleName__" , roleForm.getRoleName ( ) ) ;
		if ( roleForm.getStartTime ( ) != null ) request.setAttribute ( "startTime" , roleForm.getStartTime ( ) ) ;
		if ( roleForm.getEndTime ( ) != null ) request.setAttribute ( "endTime" , roleForm.getEndTime ( ) ) ;
		return mapping.findForward ( "roles" ) ;
	}
	
	/**
	 * 菜单授权
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadRolesFunc ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		loadRoles( mapping , form , request , response  ) ;
		return mapping.findForward ( "" ) ;
	}
	
	/**
	 * 功能授权
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadRolesFuncEls ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		loadRoles( mapping , form , request , response  ) ;
		return mapping.findForward ( "" ) ;
	}

	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward loadRole ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;

		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		byte roleType = currentUser.getUserRoleType ( ) ; 
		
		Long roleId =  roleForm.getRoleId ( );
		if ( roleId != null && roleId.longValue ( ) != 0 ) {
			RoleVo role = roleManager.getRoleById ( roleId ) ;
			request.setAttribute ( "role" , role ) ; 
		} 
		
		List options = DictionaryCache.getInstance ( ).listBizOptions ( Constants.ROLE_DIC_BIZ_KEY , false )   ;
		for ( java.util.Iterator iter = options.iterator ( ) ; iter.hasNext ( ) ;  ) {
			BizOption bizOption = ( BizOption ) iter.next ( ) ; 
			short roleType_ = GetterUtil.getShort( bizOption.getOptionValue ( ) , Constants.ROLE_TYPE_USER ) ;
			if ( roleType_ <= roleType ) {
				iter.remove ( );
			}
		}
		request.setAttribute ( "options" , options ) ;
		return mapping.findForward ( "role" ) ; 
	}
	
	
	public  ActionForward toNewRole ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		byte roleType = currentUser.getUserRoleType ( ) ; 
	
		List options = DictionaryCache.getInstance ( ).listBizOptions ( Constants.ROLE_DIC_BIZ_KEY , false )   ;
		for ( java.util.Iterator iter = options.iterator ( ) ; iter.hasNext ( ) ;  ) {
			BizOption bizOption = ( BizOption ) iter.next ( ) ; 
			short roleType_ = GetterUtil.getShort( bizOption.getOptionValue ( ) , Constants.ROLE_TYPE_USER ) ;
			if ( roleType_ <= roleType ) {
				iter.remove ( );
			}
		}
		request.setAttribute ( "options" , options ) ;
		return mapping.findForward ( "role" ) ; 
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @throws CacheException 
	 * @throws UnsupportedEncodingException 
	 */
	public ActionForward deleteRole( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws  Exception {
		StringBuffer to = new StringBuffer( "role.go?method=loadRoles" ) ; 
		
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		
		String params = EXTableUtils.getLimitParams ( request ) ;
		to.append ( params ) ;
		
		Long[] deleteIds = roleForm.getDeleteId ( );
		if ( deleteIds != null  ) {
			for ( int i = 0 ; i < deleteIds.length ; i ++ ) {
				Long deleteId = deleteIds[ i ] ;
				roleManager.deleteRole ( deleteId , getCurrentUser ( request ).getUserId ( )  ) ; 
			}
			to.append ( "&m=0" );
		}
		to.append (  "&roleType="  ).append ( String.valueOf ( roleForm.getRoleType ( ) ) ) ;
		return new ActionForward( to.toString ( ) , true ) ;
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public  ActionForward addRole( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
	
		RoleVo role = new RoleVo () ; 
		PropertyUtils.copyProperties ( role , roleForm ) ; 
		role.setCrtUser ( currentUser.getUserId ( ) );
			if ( ( roleManager.countRoles ( role.getRoleName ( ) ) ).longValue ( ) > 0 ) {
				Error error = new Error();
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.rolename.already.exist" ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;
			}
		roleManager.addRole ( role ) ; 
		return mapping.findForward ( "glsuccess"  ) ;
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @throws CacheException 
	 */
	public ActionForward updateRole( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		//StringBuffer to = new StringBuffer( "role.go?method=loadRoles" ) ; 
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 
		
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		
		/*
        java.util.Enumeration pns = request.getParameterNames();
        while( pns.hasMoreElements() ) {
        	String pn = pns.nextElement().toString();
        	if ( pn.startsWith( "ec" ) ) {
        		String pv = request.getParameter( pn ) ;
        		to.append ( "&" ).append ( pn ) .append ( "=" ).append ( URLEncoder.encode ( pv )  ) ;
        	}
        }		
		*/
		RoleVo role = new RoleVo () ; 
		PropertyUtils.copyProperties ( role , roleForm ) ; 
		role.setUpdtUser ( currentUser.getUserId ( ) ) ;
		RoleVo vo = roleManager.getRoleById(role.getRoleId());
		if (!vo.getRoleName().equals(role.getRoleName())) {
			if ((roleManager.countRoles(role.getRoleName())).longValue() > 0) {
				Error error = new Error();
				error.setErrorTitle ( OrgMessageManager.get().getMessage("org.rolename.already.exist") ) ;
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;
			}
		}
		roleManager.updateRole (  role ) ; 
		
		/*
		to.append (  "&roleType="  ).append ( String.valueOf ( role.getRoleType ( ) ) ) ;
		to.append ( "&m=0" );
		return new ActionForward( to.toString ( ) , true ) ; 
		*/
		return mapping.findForward ( "glsuccess"  ) ;
	}
	
	public  ActionForward viewUserRelation ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleVo roleVo = new RoleVo () ; 
		PropertyUtils.copyProperties ( roleVo , roleForm ) ;
		UserEmplyVo userEmplyVo = new UserEmplyVo();
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		
		EctableConverts  ec = roleVo.getEconverts ( ) ; 
        ec.setProConvert ( "crtTime" , "c.crtTime" ) ;
		EXTableUtils.initLimitPage(  roleVo , request ) ;
		Long lr = roleManager.countUserRelation ( roleVo ) ;
		roleVo.setTotalRows ( lr.intValue ( ) ) ; 
		EXTableUtils.setLimitRowAttributes(  roleVo , request ) ;
		
		List emplylist = roleManager.getUserRelation ( roleVo );
		userEmplyVo.setEmpList ( emplylist );
		request.setAttribute ( "userEmplyVo" , userEmplyVo );
		request.setAttribute ( "roleId" , roleVo.getRoleId ( ).toString ( ) );
		request.setAttribute ( "roleType" , String.valueOf ( roleVo.getRoleType ( ) ) );
		
		if ( roleForm.getLoginName ( ) != null ) request.setAttribute ( "loginName" , roleForm.getLoginName ( ) ) ;
		if ( roleForm.getEmpName ( ) != null ) request.setAttribute ( "empName" , roleForm.getEmpName ( ) ) ;
		if ( roleForm.getGrpName ( ) != null ) request.setAttribute ( "grpName" , roleForm.getGrpName ( ) ) ;
		if ( roleForm.getStartTime ( ) != null ) request.setAttribute ( "startTime" , roleForm.getStartTime ( ) ) ;
		if ( roleForm.getEndTime ( ) != null ) request.setAttribute ( "endTime" , roleForm.getEndTime ( ) ) ;

		return mapping.findForward ( "roleUserRelation" ) ; 
	}
	
	public  ActionForward viewTitleRelation ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		RoleVo roleVo = new RoleVo () ; 
		PropertyUtils.copyProperties ( roleVo , roleForm ) ;

		short roleType = ( short )roleForm.getRoleType ( ) ;
		TitleMsgVo titleMsgVo = new TitleMsgVo();
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		List titlelist = roleManager.getTitleRelation ( roleVo );
		titleMsgVo.setTitleList ( titlelist );
		
		request.setAttribute ( "titleMsgVo" , titleMsgVo );
		request.setAttribute ( "roleId" , roleVo.getRoleId ( ) );
		request.setAttribute ( "roleType" , new Short( roleType ) );
		
		if ( roleForm.getStartTime ( ) != null ) request.setAttribute ( "startTime" , roleForm.getStartTime ( ) ) ;
		if ( roleForm.getEndTime ( ) != null ) request.setAttribute ( "endTime" , roleForm.getEndTime ( ) ) ;
		if ( roleForm.getGrpName ( ) != null ) request.setAttribute ( "grpName" , roleForm.getGrpName ( ) ) ;
		if ( roleForm.getTitleName ( ) != null ) request.setAttribute ( "titleName" , roleForm.getTitleName ( ) ) ;
		
		return mapping.findForward ( "roleTitleRelation" ) ; 
	}
	
	public  ActionForward viewGroupRelation ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		Long roleId = roleForm.getRoleId ( ) ;
		short roleType = ( short )roleForm.getRoleType ( ) ;
		GroupVo groupVo = new GroupVo();
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		List grouplist = roleManager.getGroupRelation ( roleId );
		groupVo.setChildGroupList ( grouplist );
		request.setAttribute ( "groupVo" , groupVo );
		request.setAttribute ( "roleId" , roleId );
		request.setAttribute ( "roleType" , new Short( roleType ) );
		return mapping.findForward ( "roleGroupRelation" ) ; 
	}
	
	public  ActionForward viewFuncRelation ( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		RoleForm  roleForm = ( RoleForm )  form ; 
		Long roleId = roleForm.getRoleId ( ) ;
		short roleType = ( short )roleForm.getRoleType ( ) ;
		RoleManager roleManager = ( RoleManager ) getBean( "roleManager" ) ;
		List pathslist = roleManager.getFuncPaths ( roleId );
		
		FuncRoleRelVo funcRoleRel = new FuncRoleRelVo( ) ; 
		funcRoleRel.setRoleId ( roleId ) ; 
		List funcRole4fs = OrgFactory.getFunctionManager ( ).getFuncByRole4fNp ( funcRoleRel ) ;
		pathslist.addAll ( funcRole4fs ) ; 
		if ( pathslist.size ( ) > 0 ) {
			StringBuffer paths = new StringBuffer ( );
			for ( int i = 0 ; i < pathslist.size ( ) ; i ++ ) {
				FunctionVo funcvo = ( FunctionVo ) pathslist.get ( i );
				paths = paths.append ( funcvo.getPath ( ).toString ( ) ).append ( ">>" );
			}
			String funcids[] = paths.toString ( ).split ( ">>" );
			FunctionVo functionVo = new FunctionVo ( );
			functionVo.setFuncids ( funcids );
			StringBuffer sb = new StringBuffer ( );
			List funclist = roleManager.getFuncRelation ( functionVo );

			for ( int j = 0 ; j < funclist.size ( ) ; j ++ ) {
				functionVo = ( FunctionVo ) funclist.get ( j );
				/*
				if ( funcRole4fs.contains ( functionVo ) ) {
					functionVo.setFuncChn ( functionVo.getFuncChn ( ) + "(*)" ) ; 
				}*/
				for ( java.util.Iterator iter = funcRole4fs.iterator ( ) ; iter.hasNext ( ) ;  ) {
					if ( ( ( FunctionVo )iter.next ( ) ).getFuncId ( ).equals ( functionVo.getFuncId ( ) )  ) {
						functionVo.setFuncChn ( functionVo.getFuncChn ( ) + "(*)" ) ; 
					}
				}
				sb.append ( "dddddd.add(" + functionVo.getFuncId ( ) + ","
								+ functionVo.getFfuncId ( ) + ",'" + functionVo.getFuncChn ( )
								+ "','javascript:getAttachRelation(" + functionVo.getFuncId ( ) + "," + roleId + ")');" );
			}
			request.setAttribute ( "functree" , sb.toString ( ) );
		}
		request.setAttribute ( "roleId" , roleId );
		request.setAttribute ( "roleType" , new Short( roleType ) );
		return mapping.findForward ( "roleFuncRelation" ) ; 
	}
	
	/**
	 * @author zxy
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward viewComRelation ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		//response.setCharacterEncoding ( AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) ) ; 				
		String funcId = request.getParameter ( "funcId" );
		String roleId = request.getParameter ( "roleId" );
		RoleManager roleManager = ( RoleManager ) getBean ( "roleManager" );
		FuncComponentVo funcComponentVo = new FuncComponentVo ( );
		funcComponentVo.setFuncId ( Long.valueOf ( funcId ) );
		funcComponentVo.setRoleId ( Long.valueOf ( roleId ) );
		List comlist = roleManager.getComRelation ( funcComponentVo );
		JSONArray comjson = JSONArray.fromObject ( comlist ); 
		response.getWriter ( ).print ( comjson.toString ( ) );  
		response.getWriter ( ).flush ( );
		response.getWriter ( ).close ( );
		return null;
	}

}
